/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.db.dialect;  
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edi.db.EdiDb;
import com.edi.db.dialect.function.DialectFunction;
import com.edi.db.table.FieldEntity;
import com.edi.db.table.TableEntity;
import com.edi.util.StringHelper;
public class SQLServerDialect extends SybaseDialect {
	private static final Log log = LogFactory.getLog(SQLServerDialect.class);
	public SQLServerDialect(){ 
		 super();
		 registColumntypes();
	}   
	private void registColumntypes(){
		registerColumnType(Types.BIT, "bit");
		registerColumnType( Types.VARBINARY, "image" );
		registerColumnType( Types.VARBINARY, 8000, "varbinary($l)" );
	}
	
	@Override
	public String ifExitTable(String tableName) {
		String sql = "";
		sql = "select * from dbo.sysObjects where id = Object_Id(N'"
				+ tableName + "') and ObjectProperty(id, N'IsUserTable') = 1";
		return sql;
	}
	
	@Override
	public List<String> getPrimaryKeys(Connection conn,String tableName) throws SQLException{
		List<String> primaryKeys = new ArrayList<String>();
		DatabaseMetaData dbmeta = conn.getMetaData();

		if (!tableName.equalsIgnoreCase(EdiDb.TABLE_EDI_SYSTEMP)) {
			ResultSet keysRsultSet = null;
			try{
			// 获得主键信息
				keysRsultSet = dbmeta.getPrimaryKeys(null, null, tableName);
			while (keysRsultSet.next()) {
				primaryKeys
						.add(keysRsultSet.getString("COLUMN_NAME").toLowerCase());
			}
			}finally{
				if (keysRsultSet != null){
					keysRsultSet.close();
				}
			}
		}
		return primaryKeys;
	}
	
	@Override
	public String createTable(TableEntity tableEntity) {
		// StringBuilder sql= new StringBuilder();
		StringBuffer sql = new StringBuffer();
		try {
			sql.append("CREATE TABLE ").append(tableEntity.getTableName())
					.append(" (");
			Hashtable<String, FieldEntity> fields = tableEntity
					.getFieldEntitys();
			Collection<FieldEntity> set = fields.values();
			Iterator<FieldEntity> it = set.iterator();
			while (it.hasNext()) {
				FieldEntity fieldEntity = it.next();
				if (fieldEntity == null)
					continue;
				sql.append(fieldEntity.getFieldName()).append(" ");
				if (getTypeName(fieldEntity.getFieldType().sqlType()) != null)
					sql.append(getTypeName(
							fieldEntity.getFieldType().sqlType(), fieldEntity
									.getSize(), fieldEntity.getPrecision(),
							fieldEntity.getScale()));// setFieldType(fieldEntity.getFieldType().sqlType(),fieldEntity);
				if (!fieldEntity.isNullable())
					sql.append(" not null");
				if (fieldEntity.getDefaultValue() != null
						&& !"".equals(fieldEntity.getDefaultValue()))
					sql.append(" default '").append(
							fieldEntity.getDefaultValue()).append("'");
				if (fieldEntity.isIdentify())
					sql.append(" PRIMARY KEY ");
				if (it.hasNext())
					sql.append(",");
				else
					sql.append(")");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return sql.toString();
	}
	
	@Override
	public String translate(String eql) {
		if (ignoreCase)
			eql = StringUtils.lowerCase(eql);
		log.debug(" translate eql ="+eql );
		String[] eqls = StringHelper.split(StringHelper.WHITESPACE, eql);
		for (int i = 0; i < eqls.length; i++) {
			String word = eqls[i];
			if (word == null || "".equals(word))
				continue;
			DialectFunction function = getFunction(word);
			if (function != null) {
				function.process(eql, word, eqls[i]);
			}
			int beginBrack = word.indexOf("(");
			if (beginBrack > 0) {
				String functionName = word.substring(0, beginBrack);
				function = getFunction(functionName);
				if (function == null) {
					continue;
				} else {
					function.process(eql, functionName, eqls[i]);
				}
			}
		}
//		log.debug(" sql after translate ="+eql);
		return eql;
	}

}
